package com.tianya.common.mail;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessagePreparator;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.ServletContext;
import com.tianya.common.util.Utility;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class Mail {

	private JavaMailSenderImpl javaMailSenderImpl;
	private MimeMessageHelper mimeMessageHelper;
	private MimeMessage mimeMessage;
	private Boolean defaultuser;
	private ServletContext context;
	
	public Mail()
	{
		javaMailSenderImpl = (JavaMailSenderImpl)Utility.getBean("mailSender");
	}
	public Mail(Boolean defaultuser)
	{
		this.defaultuser = defaultuser;
		javaMailSenderImpl = (JavaMailSenderImpl)Utility.getBean("mailSender");
	}
	/**
	 * 由于创建发送email的新线程是，默认的Utility.getBean无法实现获得ServletContext
	 * 重新增加一个构造类，将当前的ServletContext传递过去
	 * @param defaultuser
	 * @param context
	 */
	public Mail(Boolean defaultuser, ServletContext context) {
		ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
		this.defaultuser = defaultuser;
		javaMailSenderImpl = (JavaMailSenderImpl) ctx.getBean("mailSender"); 
		this.context = context;
	}
	public Boolean send()
	{
		try
		{
			javaMailSenderImpl.send(mimeMessage); 
			return true;
		}
		catch(Exception e)
		{
			System.out.println(e);
			return false;
		}
      
	}
	@SuppressWarnings("unchecked")
	public Boolean send(String templateName,Map map)
	{
		try
		{
			TemplateEmailService templateEmailService = TemplateEmailService.getTemplateEmailService();
		
			mimeMessage.setText(templateEmailService.getMailText(templateName,map));
			if(defaultuser)
			{
				mimeMessageHelper.setFrom(templateEmailService.getDefaultuser());
			}
			javaMailSenderImpl.send(mimeMessage); 
			return true;
		}
		catch(Exception e)
		{
			System.out.println(e);
			return false;
		}
	}
	@SuppressWarnings("unchecked")
	public Boolean sendByContext(String templateName,Map map)
	{
		try
		{
			ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
			TemplateEmailService templateEmailService = (TemplateEmailService)ctx.getBean("templateEmailService");
		
			mimeMessage.setText(templateEmailService.getMailText(templateName,map));
			if(defaultuser)
			{
				mimeMessageHelper.setFrom(templateEmailService.getDefaultuser());
			}
			javaMailSenderImpl.send(mimeMessage); 
			return true;
		}
		catch(Exception e)
		{
			System.out.println(e);
			return false;
		}
	}
	/**
	 * 发送邮件，【是否为HTML格式】
	 * @param templateName 邮件模板名称
	 * @param map 邮件模板参数
	 * @param isHtml 是否为html格式
	 * @return 发送结果
	 */
	@SuppressWarnings("unchecked")
	public Boolean send(String templateName,Map map,Boolean isHtml)
	{
		try
		{
			TemplateEmailService templateEmailService = TemplateEmailService.getTemplateEmailService();
		
			mimeMessageHelper.setText(templateEmailService.getMailText(templateName,map), isHtml);
			if(defaultuser)
			{
				mimeMessageHelper.setFrom(templateEmailService.getDefaultuser());
			}
			javaMailSenderImpl.send(mimeMessage); 
			return true;
		}
		catch(Exception e)
		{
			System.out.println(e);
			return false;
		}
	}
	
	/**
	 * 发送带附件的邮件
	 * @param templateName	模板名
	 * @param map	模板参数集合
	 * @param files	附件集合
	 * @param emais 发送邮箱集合
	 * @param title 邮件标题
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public boolean send(final String templateName,final Map map,final List<File> files,final InternetAddress[] emails,final String title) {
		try {
			MimeMessagePreparator mimeMail = new MimeMessagePreparator() {
	            public void prepare(MimeMessage mimeMessage) throws MessagingException {
	            	//设置收件人
	                mimeMessage.setRecipients(Message.RecipientType.TO, emails);
	                TemplateEmailService templateEmailService = TemplateEmailService.getTemplateEmailService();
	                //设置发件人
	                if(defaultuser) {
	                	mimeMessage.setFrom(new InternetAddress(templateEmailService.getDefaultuser()));
	    			}
	                //添加标题
	                mimeMessage.setSubject(Utility.isEmpty(title)?"无标题":title, "UTF-8"); 
	                
	                Multipart mp = new MimeMultipart();
	                
	                //向Multipart添加正文
	                MimeBodyPart content = new MimeBodyPart();
	                content.setText(templateEmailService.getMailText(templateName,map));
	                //向MimeMessage添加（Multipart代表正文）
	                mp.addBodyPart(content);
	                
	                //向Multipart添加附件
	                for(File file:files) {
	                    MimeBodyPart attachFile = new MimeBodyPart();
	                    FileDataSource fds = new FileDataSource(file);
	                    attachFile.setDataHandler(new DataHandler(fds));
	                    attachFile.setFileName(fds.getName());
	                    mp.addBodyPart(attachFile);
	                }
	                
	                files.clear();
	                
	                //向Multipart添加MimeMessage
	                mimeMessage.setContent(mp);
	                mimeMessage.setSentDate(new Date());
	            }
	        };
	        javaMailSenderImpl.send(mimeMail);
			return true;
		} catch(Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public MimeMessageHelper  getMessageHelper()
	{
		try
		{
			mimeMessage =  javaMailSenderImpl.createMimeMessage();
			mimeMessageHelper =  new MimeMessageHelper(mimeMessage,true,"GBK");
			return mimeMessageHelper;
		}
		catch(Exception e)
		{
			System.out.println(e);
			return null;
		}
	}
}
